package com.bsh.repository;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import com.bsh.mybatis.IRepository.MerchantImgMapper;
import com.bsh.mybatis.model.MerchantImg;
import com.bsh.utils.Pager;
import com.mysql.jdbc.StringUtils;
@Repository
public class DaoMerchantImg {
	@Resource
	SqlSessionTemplate session;
	@Resource
	JdbcTemplate jdbcTemplate;
	@Resource
	NamedParameterJdbcTemplate namedJdbcTemplate;
	
	MerchantImgMapper getMerchantImgMapper(){
		return session.getMapper(MerchantImgMapper.class);
	}
	
	MerchantImgMapper getMapper() {
		return session.getMapper(MerchantImgMapper.class);
	}

	public int deleteByPrimaryKey(Integer id) {
		int res = getMapper().deleteByPrimaryKey(id);
		return res;
	}

	public int insert(MerchantImg record) {
		int res = getMapper().insert(record);
		return record.getId();
	}

	public int insertSelective(MerchantImg record) {
		int res = getMapper().insertSelective(record);
		return record.getId();
	}

	public MerchantImg selectByPrimaryKey(Integer id) {
		MerchantImg row = getMapper().selectByPrimaryKey(id);
		return row;
	}

	public int updateByPrimaryKeySelective(MerchantImg record) {
		int res = getMapper().updateByPrimaryKeySelective(record);
		return res;
	}

	public int updateByPrimaryKey(MerchantImg record) {
		int res = getMapper().updateByPrimaryKey(record);
		return res;
	}
	

	/**
	 * 图片分页查询
	 */
	public List<Map<String, Object>> getPage(Pager pager, String where) {
		StringBuilder sb = new StringBuilder();
		MapSqlParameterSource ps = new MapSqlParameterSource();
		sb.append("SELECT g.*,m.name,m.merchant_name ");
		sb.append("FROM	merchant_img g ");
		sb.append("join merchant m on m.id=g.merchant_id ");
		sb.append("WHERE 1 = 1 ");		
		if (!StringUtils.isNullOrEmpty(where)) {
			sb.append(where);
		}
		Integer count = namedJdbcTemplate.queryForInt("select count(0) from (" + sb.toString() + ")v", ps);

		sb.append(" order by g.id desc limit :start,:size");
		ps.addValue("start", pager.getStart());
		ps.addValue("size", pager.getPageSize());
		List<Map<String, Object>> list = namedJdbcTemplate.queryForList(sb.toString(), ps);

		pager.setRowCount(count);
		return list;
	}	
	
	/**
	 * 查询商家的列表
	 * @param id
	 * @return
	 */
	public List<MerchantImg> getMerchantImgList(Integer merchantId){
		List<MerchantImg> res = getMapper().getMerchantImgList(merchantId);
		return res;
	}
	
}
